﻿//by  张海军 710605420@qq.com
#if HOTFIX_ENABLE

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using XLua;
using System;
using LazyFramework.UI;

namespace LazyFramework.LUA.UI
{

    public class LuaUIManager : Singleton<LuaUIManager> {

        /// <summary>
        /// 所有 Lua 实现的 UI 定义，[ViewClassName, LuaFilePath]
        /// </summary>
        public Dictionary<string, string> luaUINames { get; private set; }

        /// <summary>
        /// 所有存在的 luaUI 实例, [string,[string,LuaViewRunner]]
        /// </summary>
        public Dictionary<string, List<WeakReference>> luaUIInstances { get; private set; }

        public LuaUIManager() {
            luaUIInstances = new Dictionary<string, List<WeakReference>>();
            luaUINames = new Dictionary<string, string>();
        }

        public void SetLuaUIs(Dictionary<string, string> luaUIs) {
            luaUINames = luaUIs;
        }

        /// <summary>
        /// 添加一个 luaUI
        /// </summary>
        /// <param name="runner"></param>
        public void AddLuaUI(UILuaViewControllerBase runner) {
            List<WeakReference> runnerList = null;
            if (!luaUIInstances.TryGetValue(runner.viewClassName, out runnerList)) {
                runnerList = new List<WeakReference>();
                luaUIInstances.Add(runner.viewClassName, runnerList);
            }

            runnerList.Add(new WeakReference(runner));
        }

        /// <summary>
        /// 移除一个 luaUI
        /// </summary>
        /// <param name="runner"></param>
        /// <returns></returns>
        public bool RemoveLuaUI(UILuaViewControllerBase runner) {
            List<WeakReference> runnerList = null;
            if (!luaUIInstances.TryGetValue(runner.viewClassName, out runnerList)) {
                return false;
            }

            int cnt = runnerList.Count;
            for(int i = 0; i < cnt; i++) {
                if(ReferenceEquals(runnerList[i].Target, runner)) {
                    runnerList.RemoveAt(i);
                    return true;
                }
            }

            return false;
        }

        public void Clear()
        {
            luaUIInstances.Clear();
        }
    }
}

#endif